package com.zl.learning.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.stream.IntStream;

public class Test2 {

    public static void main(String[] args) {
        Test2 main = new Test2();
        main.parallelThread();
        System.out.println("--------------------");
        main.singleThread();
    }

    private void parallelThread() {
        Long start = System.currentTimeMillis();
        IntStream.range(0, 8).parallel().forEach(r -> insert(100));
        Long end = System.currentTimeMillis();
        System.out.println("total:" + (end - start));
    }

    private void singleThread() {
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 8; i++) {
            insert(100);
        }
        Long end = System.currentTimeMillis();
        System.out.println("total:" + (end - start));
    }

    public Connection getConn() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/druid?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true", "root", "*Jsnjcc*");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**  本地连服务器76 平均 45条/秒     本地 SSD 平均357条/秒     本地 机械 平均 33条/秒
     * 1000   const:21606               const:2959               const:30333
     * 10*100 const:28138               const:2967               const:29342
     * 5*200  const:24246               const:2532               const:32902
     * 2*500  const:26695               const:2812               const:29952
     */
    private void insert(int count) {
        long start = System.currentTimeMillis();
        String sql = "INSERT INTO `tbl_dept`(`name`, `parent_id`, `root_parent_id`) VALUES (?, ?, ?)";
        try (Connection conn = getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            for (int i = 0; i < count; i++) {
                pstmt.setString(1, "省厅123qweqwe批次0号码20");
                pstmt.setInt(2, -1);
                pstmt.setInt(3, -1);
                pstmt.addBatch();
            }
            pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("const:" + (end - start));
    }
}
